﻿using System;
using System.Collections.Generic;
using System.Linq;
#if !NETCOREAPP
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
    using System.Web.Mvc.Html;

#endif

#if NETCOREAPP
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Http.Extensions;
using Kugar.Core.Web;
#endif
using Kugar.Core.ExtMethod;
using Kugar.MVC.MobileUI.WeUI.Enum;
using Kugar.MVC.MobileUI.WeUI.Helpers;
using Kugar.MVC.MobileUI.WeUI.PageControls.PageCommons;


namespace Kugar.MVC.MobileUI.WeUI.PageControls.PageForm
{
    public class PageForm_Form : ContainerBase
    {
        private string _formMethod = "get";
        private string _formUrl = "";
        private bool _isAjax = false;
        private FormEnctype _enctype = FormEnctype.multipart;
        private LinkTargetType _targetType = LinkTargetType.Self;
        private string _updateElementID = "";
        private List<ButtonItemBase> _buttomBtns = new List<ButtonItemBase>();
        private Lazy<List<KeyValuePair<string,string>>> _hiddenValues=new Lazy<List<KeyValuePair<string, string>>>();

        public PageForm_Form(ViewContext viewContext) : base(viewContext)
        {
        }

        public PageForm_Form Enctype(FormEnctype enctype = FormEnctype.Application_urlencoded)
        {
            _enctype = enctype;

            return this;
        }

        public PageForm_Form WithHiddenValue(string name, string value)
        {
            _hiddenValues.Value.Add(new KeyValuePair<string, string>(name,value));

            return this;
        }

        public PageForm_Form Target(LinkTargetType targetType = LinkTargetType.Self)
        {
            _targetType = targetType;

            return this;
        }

        public PageForm_Form Post(string postUrl = "")
        {
            _formMethod = "POST";

            if (!string.IsNullOrWhiteSpace(postUrl))
            {
                _formUrl = postUrl;
            }


            return this;
        }

        public PageForm_Form Get(string getUrl = "")
        {
            _formMethod = "GET";

            if (!string.IsNullOrWhiteSpace(getUrl))
            {
                _formUrl = getUrl;
            }

            return this;
        }

        public PageForm_Form Ajax(bool isAjax = true)
        {
            _isAjax = isAjax;

            return this;
        }

        public PageForm_Form UpdateElementID(string elementID)
        {
            _updateElementID = elementID;

            return this;
        }

        //public PageForm_Form AddButton(Action<ButtonItemBase> config)
        //{
        //    var cfg = new ButtonItemBase();

        //    config(cfg);

        //    _buttomBtns.Add(cfg);

        //    return this;
        //}

        public override void Dispose()
        {
            ViewContext.Writer.WriteLine("</div> <!-- End weui-cells_form -->");

            OutForm();

            ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");

            if (_buttomBtns.HasData())
            {
                foreach (var btn in _buttomBtns)
                {
                    ViewContext.Writer.WriteLine(
                        $"<button class=\"{Utility.ButtonStyleToStr(btn.getButtonStyle)}\" {(btn.getOnClickScript.IsNotNullOrEmpty() ? $"onclick=\"{btn.getOnClickScript}\"" : "")} id=\"{btn.getID}\" type=\"{Utility.ButtonTypeToStr(btn.getType)}\">{btn.getText}</button>");
                }
            }

            if (_hiddenValues.IsValueCreated && _hiddenValues.Value.HasData())
            {
                foreach (var v in _hiddenValues.Value)
                {
                    ViewContext.Writer.WriteLine($"<input type=\"hidden\" name=\"{v.Key}\" value=\"{v.Value}\" />");
                }
            }

            ViewContext.Writer.WriteLine($"</{(IsInForm() ? "div" : "form")}>");
        }

        internal override ContainerBase RenderInternal()
        {
            if (!string.IsNullOrWhiteSpace(_formUrl))
            {
                _attrs.MergeAttr("action", _formUrl);
            }
            else
            {
#if NETCOREAPP
                _attrs.MergeAttr("action", ViewContext.HttpContext.Request.GetDisplayUrl());

#endif
#if !NETCOREAPP
       _attrs.MergeAttr("action", ViewContext.HttpContext.Request.RawUrl);
#endif

            }

            _attrs.MergeAttr("method", _formMethod.ToUpper());
            _attrs.MergeAttr("enctype", Utility.FormEncTypeToStr(_enctype));

            if (_isAjax)
            {
                _attrs.MergeAttr("data-ajax", _isAjax.ToStringEx());
            }

            if (!string.IsNullOrWhiteSpace(_updateElementID))
            {
                _attrs.MergeAttr("data-updateelemid", _updateElementID);
            }

            if (_targetType != LinkTargetType.Self)
            {
                _attrs.MergeAttr("target", Utility.LinkTargetToStr(_targetType));
            }

            var isInForm = IsInForm();

            if (!isInForm)
            {
                ViewContext.Writer.WriteLine("<form class=\"fakeform\"></form>");
            }
            else
            {
                _attrs.MergeAttr("data-innerform", "True");
            }

            ViewContext.Writer.WriteLine($"<{(isInForm ? "div" : "form")} {_attrs}>");

            ViewContext.Writer.WriteLine("<div class=\"weui-cells weui-cells_form\">");

            EnterForm();

            return this;
        }

        private bool IsInForm()
        {
            var count = (int) ViewContext.TempData.TryGetValue("FormCount", 0);

            return count > 0;
        }

        private void EnterForm()
        {
            var count = (int) ViewContext.TempData.TryGetValue("FormCount", 0);


            ViewContext.TempData.AddOrUpdate("FormCount", count + 1);
        }

        private void OutForm()
        {
            var count = (int) ViewContext.TempData.TryGetValue("FormCount", 0);

            if (count <= 0)
            {
                return;
            }

            ViewContext.TempData.AddOrUpdate("FormCount", count - 1);
        }
    }
}